package com.zyf.apitest.source;

import com.zyf.apitest.beans.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;

/**
 * @author Malegod_xiaofei
 * @create 2021-12-27-9:18
 */
public class SourceTest4_UDF {
    public static void main(String[] args) throws Exception {
        // 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 设置并行度
        env.setParallelism(1);

        // 自定义 source
        DataStreamSource<SensorReading> dataStream = env.addSource(new MySensorSource());

        // 打印输出
        dataStream.print("data");

        // 执行
        env.execute("test");
    }

    // 实现自定义的 sourceFunction
    public static class MySensorSource implements SourceFunction<SensorReading> {

        // 定义一个标志位，来控制数据的产生
        private boolean running = true;

        public void run(SourceContext<SensorReading> ctx) throws Exception {
            // 定义一个随机数发生器
            Random random = new Random();

            // 设置 10 个传感器的初始温度
            HashMap<String, Double> sensorTempMap = new HashMap<String, Double>();
            for (int i = 0; i < 10; i++) {
                sensorTempMap.put("sensor_" + (i + 1), 60 + random.nextGaussian() * 20);
            }
            while (running) {
                for (String sensorId : sensorTempMap.keySet()) {
                    // 在当前温度的基础上随机波动
                    Double newTemp = sensorTempMap.get(sensorId) + random.nextGaussian();
                    sensorTempMap.put(sensorId, newTemp);
                    ctx.collect(new SensorReading(sensorId, System.currentTimeMillis() / 1000, newTemp));
                }
                // 控制输出频率
                Thread.sleep(1000L);
            }
        }

        public void cancel() {
            running = false;
        }
    }
}
